/* eslint-disable valid-jsdoc */
const db = require('../models');
const jwt = require('jsonwebtoken');
const secret = 'bbsGouLiZhi*@!***';
function common() {
    return async (ctx, next) => {
        /**
         * 全局成功返回
         * @param data
         */
        ctx.success = function (data = '') {
            ctx.body = { code: 0, msg: 'success', data: data };
            return;
        };
        /**
         * 错误返回
         * error
         * @param msg
         */
        ctx.errors = function (msg = 'error') {
            ctx.body = { code: 1, msg: msg, data: '' };
            return false;
        };
        /**
         * token 生产token
         * @param username
         * @param role
         * @param expires
         * @param strTimer
         * @returns {*}
         */
        ctx.createToken = (user, id, expires, strTimer) => {
            let token = jwt.sign({
                User: user,
                role: { role: id }
            }, secret, {
                    expiresIn: expires + ' ' + strTimer
                });
            return token;
        };
        /**
         * 全局database模型
         * @type {Sequelize|db}
         */
        ctx.db = db;
        /**
         * Op
         * @type {{adjacent: typeof adjacent; all: typeof all; and: typeof and; any: typeof any; between: typeof between; col: typeof col; contained: typeof contained; contains: typeof contains; endsWith: typeof endsWith; eq: typeof eq; gt: typeof gt; gte: typeof gte; iLike: typeof iLike; in: typeof in; iRegexp: typeof iRegexp; is: typeof is; like: typeof like; lt: typeof lt; lte: typeof lte; ne: typeof ne; noExtendLeft: typeof noExtendLeft; noExtendRight: typeof noExtendRight; not: typeof not; notBetween: typeof notBetween; notILike: typeof notILike; notIn: typeof notIn; notIRegexp: typeof notIRegexp; notLike: typeof notLike; notRegexp: typeof notRegexp; or: typeof or; overlap: typeof overlap; placeholder: typeof placeholder; regexp: typeof regexp; startsWith: typeof startsWith; strictLeft: typeof strictLeft; strictRight: typeof strictRight; substring: typeof substring}}
         */
        ctx.Op = db.Op;
        await next();
    };
}
module.exports = common;
